package com.fengmi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.fengmi.entity.SysPermission;
import com.fengmi.entity.SysRole;
import com.fengmi.entity.SysUser;
import com.fengmi.mapper.UserMapper;
import com.fengmi.service.UserService;
import com.fengmi.vo.ResultVO;
import com.util1.JwtUtils;
import com.util1.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.security.PrivateKey;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultVO login(SysUser sysUser) {

        if (sysUser == null) {
            return new ResultVO(false,"用户名或者密码不正确");
        }

        //根据用户名获取用户信息
        SysUser userFromDB = userMapper.findUserByUserName(sysUser.getUserName());

        if (userFromDB == null) {
            return new ResultVO(false,"用户名或者密码不正确");
        }

        //比较密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

       if(! encoder.matches(sysUser.getPassword(),userFromDB.getPassword())){
            return new ResultVO(false,"用户名或者密码不正确");

       }


       //封装主体信息，（令牌的payload中）
       userFromDB.setPassword("");

       //获取用户的角色信息
       List<SysRole> rolesByUserId = userMapper.findRolesByUserId(userFromDB.getUserId()+"");

       List<String> roleListString = rolesByUserId.stream().map(role -> role.getRoleName()).collect(Collectors.toList());

        //获取用户的权限信息
        List<SysPermission> permissionByUserId = userMapper.findPermissionByUserId(userFromDB.getUserId() + "");
        List<String> permissListString = permissionByUserId.stream().map(permiss -> permiss.getPermName()).collect(Collectors.toList());

        userFromDB.setPermissions(StrUtil.join(",",permissListString));
        userFromDB.setRoles(StrUtil.join(",",roleListString));



        //颁发jwt令牌
        //获取私钥
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(ResourceUtils.getFile("classpath:rsa.pri").getPath());

            String token = JwtUtils.generateTokenExpireInMinutes(userFromDB, privateKey, 10);

            return  new ResultVO(true,"login success",token);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVO(false,"用户名或者密码不正确");
        }


    }
}
